package com.abner.juc.util;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    /**
     * 一共有3个车位有6个车抢
     * 抢到车位的3秒钟后离开车位
     * 空出来的车位剩下没抢到的抢
     */
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread( () -> {
                try {
                    semaphore.acquire(); //获取 当前信号量减一
                    System.out.println(Thread.currentThread().getName()+"\t抢占到了车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"\t离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("-----");
                    semaphore.release(); //释放 信号量加1 唤醒等待的线程
                }
            },String.valueOf(i)).start();
        }
    }
}
